package com.easybuy.util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.easybuy.entity.Product;

public class ShoppingCart implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	//商品集合，key：商品的id， value：ShoppingCartItem
	private Map<Integer, ShoppingCartItem> items = new HashMap<Integer, ShoppingCartItem>();
	private Double sum; //总计

	
	/**
	 * 向购物车中添加商品
	 * @param product
	 * @param quantity
	 */
	public void addItem(Product product,int quantity){
		ShoppingCartItem item = null;
		//查看购物车中有没有该商品
        // 如果有该商品就直接加quantity
        if (items.containsKey(product.getId())) {
        	item = items.get(product.getId());
        	item.setQuantity(item.getQuantity()+quantity);
			
		} else {
			// 如果没有该商品就新建一个item
			item = new ShoppingCartItem(product, quantity);
			// 添加到items中
			items.put(product.getId(), item);
		}
        
        calSum();
	}
	
	/**
	 * 计算购物车总金额
	 */
	public void calSum(){
		
		Double sumNew = 0.0;
		
		Iterator<ShoppingCartItem> iterator = items.values().iterator();
		while(iterator.hasNext()){
			sumNew += iterator.next().getCost();
		}
		this.sum = sumNew;
	}

	public Map<Integer, ShoppingCartItem> getItems() {
		return items;
	}

	public void setItems(Map<Integer, ShoppingCartItem> items) {
		this.items = items;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public Double getSum() {
		return sum;
	}

	public void setSum(Double sum) {
		this.sum = sum;
	}
}
